<?php
/**
 * @author renjianhong
 * @date 2021-10-28
 */
namespace Modules\Order\Services\Api;

use App\Models\Area;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Order\Entities\BaseModel;
use Modules\Order\Entities\Order;
use Modules\Order\Entities\Cart;
use Modules\Order\Entities\GoodsCat;
use Modules\Order\Entities\GoodsCats;
use Modules\Order\Entities\Goods;
use Modules\Order\Entities\UserLevel;
use Modules\Order\Entities\User;
use Modules\Order\Entities\OrderWarn;
use Modules\Order\Entities\OrderDetail;
use Modules\Order\Entities\OrderRefund;
use Modules\Order\Entities\WechatAppletSetting;
use Modules\Order\Entities\ShareSetting;
use Modules\Order\Entities\ShareLog;

use function Sodium\compare;

use EasyWeChat\Factory;
use function EasyWeChat\Kernel\Support\generate_sign;

class OrderPayDataServices extends BaseService
{
    /**
     * @var Request
     */
    private $request;
    private $share_setting;
    private $order;
    private $user;

    private $app_id;
    private $mch_id;
    private $key;

    /**
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->app_id = WechatAppletSetting::where('code','app_id')->value('value');
        $this->mch_id = WechatAppletSetting::where('code','mch_id')->value('value');
        $this->key = WechatAppletSetting::where('code','mch_key')->value('value');
        
        $notify_url = url('api/order/notify');
        $config = [
            // 必要配置
            'app_id'             => $this->app_id,
            'mch_id'             => $this->mch_id,//服务商商户号
            'key'                => $this->key,   // API 密钥
            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => '', // XXX: 绝对路径！！！！
            'key_path'           => '',      // XXX: 绝对路径！！！！
            'notify_url'         => $notify_url,
        ];
        $app = Factory::payment($config);
        $this->app = $app;
        $this->notify_url = $notify_url;
        $this->request = $request;
        
    }

    /**
     * 订单支付数据
     */
    public function search()
    {
        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");
        $order_id = $this->request->input('order_id');
        $pay_type = $this->request->input('pay_type');
        if(empty($pay_type)) throw new \Exception("支付方式错误");
        $this->user = User::find($user_id);
        
        $this->user->money = doubleval($this->user->money);
        
        if ($order_id) { //单个订单付款
            $this->order = Order::where([
                ['id' ,'=', $order_id],
            ])->first();
            if (!$this->order) {
                throw new \Exception("订单不存在");
            }
            if ($this->order->is_delete == 1 || $this->order->order_status == 4) {
                throw new \Exception("订单已取消");
            }
            
            $goods_names = '';
            $goods_list = OrderDetail::where([
                ['order_id' ,'=', $this->order->id],
                ['is_delete' ,'=', 0],
            ])->select('goods_name')->get()->toArray();
            foreach ($goods_list as $goods) {
                $goods_names .= $goods['goods_name'] . ';';
            }
            $goods_names = mb_substr($goods_names, 0, 32, 'utf-8');
            //更新佣金
            $this->setReturnData($this->order);
            //更新订单数据
            $this->order->save();
            if ($pay_type == 'WECHAT_PAY') {
                if($this->order->pay_price == 0){

                    throw new \Exception("订单金额必须大于0");
                    $this->order->order_status = 1;
                    $this->order->pay_type = 1;
                    $this->order->pay_time = date("Y-m-d H:i:s");
                    $this->order->save();

                    //支付完成后，相关操作
                    $form = new OrderWarn();
                    $form->order_id = $this->order->id;
                    $form->order_type = 0;
                    $form->notify();
                    $data = [
                        'price' => 0
                    ];
                    return $data;
                }
                
                $res = $this->wechatPay($goods_names,$this->order);
                
                return $res;
            }
            //货到付款和余额支付数据处理
            if ($pay_type == 'HUODAO_PAY' || $pay_type == 'BALANCE_PAY') {
                $order = $this->order;
                //余额支付  用户余额变动
                if ($pay_type == 'BALANCE_PAY') {
                    $user = User::where('id' , $order->user_id)->first();
                    if ($user->money < $order->pay_price) {
                        throw new \Exception("支付失败，余额不足");
                    }
                    $user->money -= floatval($order->pay_price);
                    $user->save();
                    $order->order_status = 1;
                    $order->pay_type = 1;
                    $order->pay_time = date("Y-m-d H:i:s");
                    $order->save();
                }
                //支付完成后，相关操作
                $form = new OrderWarn();
                $form->order_id = $order->id;
                $form->order_type = 0;
                $form->notify();
                
                return true;
            }
        }
    }

    /**
     * 设置佣金
     * @param Order $order
     */
    private function setReturnData($order)
    {
        $setting = ShareSetting::first();
        
        if (!$setting || $setting->level == 0) {
            return false;
        }
        if(isset($this->order->mch_id) && $this->order->mch_id > 0){
            $mchSetting = MchSetting::where('mch_id' , $this->order->mch_id);
            if(!$mchSetting){
                return false;
            }
            if($mchSetting->is_share == 0){
                return false;
            }
        }
        $orderDetail = $this->getOrderDetail();   
        
        if (!$orderDetail) {
            return false;
        }
        $user = User::find($this->order->user_id);
        if (!$user) {
            return false;
        }
        
        if ($order->type == 0) {
            /* @var $orderShare Order */
            $orderShare = $this->order;
            
            if ($user->parent_id_1) {
                $parent = User::find($user->parent_id_1);//上级
                $orderShare->parent_id_1 = $parent->id;
                if ($parent->parent_id_1) {
                    //$parent_1 = User::find($parent->parent_id_1);//上上级
                    $orderShare->parent_id_2 = $parent->parent_id_1;
                } else {
                    $orderShare->parent_id_2 = -1;
                }
            } else {
                $orderShare->parent_id_1 = -1;
                $orderShare->parent_id_2 = -1;
            }
            
        }
        
        $share_commission_money_first = 0;//一级分销总佣金
        $share_commission_money_second = 0;//二级分销总佣金
        $share_commission_money_rebate = 0;//自购返利
        foreach ($orderDetail as $item) {
            $item_price = doubleval($item['price']);
            
            if ($item['individual_share'] == 1) {
                $rate_first = doubleval($item['share_commission_first']);
                $rate_second = doubleval($item['share_commission_second']);
                $rate_rebate = doubleval($item['rebate']);
                $shareType = $item['share_type'];
                
            } else {
                if(isset($item['mch_id']) && $item['mch_id'] > 0){
                    continue;
                }
                $rate_first = doubleval($setting->first);
                $rate_second = doubleval($setting->second);
                $rate_rebate = doubleval($setting->rebate);
                $shareType = $setting->price_type;
            }
            
            if ($shareType == 1) {
                $share_commission_money_first += $rate_first * $item['num'];
                $share_commission_money_second += $rate_second * $item['num'];
                $share_commission_money_rebate += $rate_rebate * $item['num'];
            } else {
                $share_commission_money_first += $item_price * $rate_first / 100;
                $share_commission_money_second += $item_price * $rate_second / 100;
                $share_commission_money_rebate += $item_price * $rate_rebate / 100;
            }
        }

        if ($setting->is_rebate == 1 && $user->is_distributor == 1) {
            $orderShare->rebate = $share_commission_money_rebate < 0.01 ? 0 : $share_commission_money_rebate;
            $orderShare->first_price = $share_commission_money_first < 0.01 ? 0 : $share_commission_money_first;
            $orderShare->second_price = $share_commission_money_second < 0.01 ? 0 : $share_commission_money_second;
        } else {
            $orderShare->rebate = 0;
            $orderShare->first_price = $share_commission_money_first < 0.01 ? 0 : $share_commission_money_first;
            $orderShare->second_price = $share_commission_money_second < 0.01 ? 0 : $share_commission_money_second;
        }
        
        $orderShare->save();

        $order = Order::find($order->id);
        $share_setting = ShareSetting::first();
        if ($order->rebate > 0) {
            ShareLog::set($order->user_id, $order->id, $order->user_id, 20, 0, $order->pay_price, $order->rebate, 0,0,'自购返利');
        }
        if ($share_setting->level >= 1) {
            ShareLog::set($order->parent_id_1, $order->id, $order->user_id, 10, 10, $order->pay_price, $order->first_price, 0,1,'一级佣金');
        }
        if ($share_setting->level >= 2) {
            ShareLog::set($order->parent_id_2, $order->id, $order->user_id, 10, 20, $order->pay_price, $order->second_price, 0,2,'二级佣金');
        }
        
        return;
    }

    /**
     * 获取商品详情
     */
    private function getOrderDetail()
    {
        /* @var $order Order */
        $order = $this->order;
        /* @var $list OrderDetail */
        $list = OrderDetail::where([['is_delete' ,'=', 0], ['order_id' ,'=', $order->id]])->get();
        
        $newList = [];
        foreach ($list as $key => $value) {
            $goods = Goods::find($value->goods_id)->toArray();
            $newItem = [
                'individual_share' => $goods['share_open'],
                'share_commission_first' => $goods['share_commission_first'],
                'share_commission_second' => $goods['share_commission_second'],
                'share_type' => $goods['share_type'],
                'num' => $value['goods_num'],
                'price' => $value['pay_price'],
                'rebate' => $value['rebate']
            ];
            array_push($newList, $newItem);
        }
        return $newList;
    }

    private function unifiedOrder($goods_names,$order)
    {
        $url = BaseModel::getHttps().$_SERVER['SERVER_NAME']."/api/pay/wechat-pay";
        $post_data['user_id'] = $order->user_id;
        $post_data['order_no'] = $order->order_no;
        $post_data['body'] = $goods_names;
        $post_data['price'] = $order->pay_price;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//用post方法传送参数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    /**
     * 微信支付统一下单
     */
    public function wechatPay($body,$order)
    {
        $user = User::where('id',$order->user_id)->first();
        
        $unify = $this->app->order->unify([
            'body' => $body,
            'out_trade_no' => $order->order_no,
            'total_fee' => $order->pay_price * 100,
            'notify_url' => $this->notify_url,
            'trade_type' => 'JSAPI',
            'openid' => $user->openid,
        ]);
        
        if ($unify['return_code'] === 'SUCCESS' && !isset($unify['err_code'])) {
            $pay = [
                'appId' => $this->app_id,
                'timeStamp' => (string) time(),
                'nonceStr' => $unify['nonce_str'],
                'package' => 'prepay_id=' . $unify['prepay_id'],
                'signType' => 'MD5',
            ];

            $pay['paySign'] = generate_sign($pay, $this->key);

            return $pay;
        } else {
            
            $unify['return_code'] = 'FAIL';
            return $unify;
        }
        
    }

    /**
     * 支付通知
     */
    public function notify()
    {
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            $out_trade_no = $message['out_trade_no']; // 商户订单号
            $trade_no = $message['transaction_id'];  // 微信支付订单号
            //$file = file_put_contents(public_path("tttt.txt"),$out_trade_no);
            $order = Order::where([['order_no','=',$out_trade_no]])->first();
            if (!$order || $order->order_status == 1) {
                return true; //告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    $order->transaction_no = $trade_no;
                    $order->order_status = 1;
                    $order->pay_type = 0;
                    $order->pay_time = date("Y-m-d H:i:s");
                    $order->save();
                    //后台订单提醒
                    OrderMessage::set($order->id, $this->order_type, 0);
                    return true;
                }elseif ($message['result_code'] === 'FAIL') {  // 用户支付失败
                    
                    throw new \Exception("支付失败，请重试");
                }
                
            } else {
                throw new \Exception("支付失败，请重试");
            }
            return true;
        });
        return $response;
    }

}